package com.xyf.basicrtc

import android.util.Log
import org.java_websocket.WebSocket
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.handshake.ServerHandshake
import java.lang.Exception
import java.net.URI
import java.nio.ByteBuffer

class SocketClient(uri: URI) : WebSocketClient(uri) {
    companion object {
        const val TAG = "SocketLive"
    }

    var onRemoteFrame: ((ByteArray) -> Unit)? = null

    override fun onOpen(handshakedata: ServerHandshake?) {
        Log.i(TAG, "onOpen")
    }

    override fun onClose(code: Int, reason: String?, remote: Boolean) {
        Log.i(TAG, "onClose")
    }

    override fun onMessage(message: String?) {
        Log.i(TAG, "onMessage")
    }

    override fun onError(ex: Exception?) {
        Log.i(TAG, "onError ${ex?.message}")
    }

    override fun onMessage(bytes: ByteBuffer?) {
        super.onMessage(bytes)
        onRemoteFrame?.run {
            bytes?.let {
                val buf = ByteArray(it.remaining())
                it.get(buf)
                this(buf)
            }
        }
    }


    fun sendData(h265: ByteArray) {
        if (isOpen){
            send(h265)
        }
    }
}